import { _decorator, AudioClip, AudioSource, Component, Director, director, game, Node } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('playAudio')
export class playAudio extends Component {

    @property(AudioSource)
    public bgm: AudioSource = null!;

    private static instance: playAudio;

    onLoad(): void {
        game.addPersistRootNode(this.node);
    }
    start() {
        
        if (playAudio.instance) {
            this.destroy();
            return;
        }
        playAudio.instance = this;
        Director.instance.on(Director.EVENT_AFTER_SCENE_LAUNCH, this.handleSceneSwitch, this);
        this.playBGM();

        this.bgm.clip.on('ended', () => {
            this.bgm.play();
        });
    }

    playBGM() {
        if (this.bgm && !this.bgm.playing) {
            this.bgm.play();
        }
    }

    handleSceneSwitch() {
        this.playBGM();
    }
    
}

